<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chic Core - Vue Utils 演示</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
            background-color: #f5f5f5;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            margin: 0;
            font-size: 2.5rem;
            font-weight: 300;
        }
        
        .header p {
            margin: 0.5rem 0 0 0;
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .loading {
            text-align: center;
            padding: 2rem;
            font-size: 1.1rem;
            color: #666;
        }
        
        .error {
            background-color: #ffebee;
            color: #c62828;
            padding: 1rem;
            border-radius: 4px;
            margin: 1rem 0;
            border-left: 4px solid #f44336;
        }
        
        .github-link {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(255,255,255,0.9);
            color: #333;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            text-decoration: none;
            font-size: 0.9rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .github-link:hover {
            background: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="header">
            <h1>Chic Core</h1>
            <p>前端常用工具函数库 - Vue 演示</p>
        </div>
        
        <div class="container">
            <div class="loading">
                <p>正在加载演示页面...</p>
                <p>如果长时间未加载，请检查控制台错误信息</p>
            </div>
        </div>
    </div>
    
    <a href="https://github.com/yourusername/chic-core" class="github-link" target="_blank">
        📦 GitHub
    </a>

    <!-- 引入Vue 3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    
    <!-- 引入Chic Core -->
    <script src="./dist/index.umd.js?v=2"></script>
    
    <script>
        const { createApp } = Vue;
        
        // 检查ChicCore是否加载成功
        if (typeof ChicCore === 'undefined') {
            document.querySelector('.container').innerHTML = `
                <div class="error">
                    <h3>❌ 加载失败</h3>
                    <p>无法加载 ChicCore 库，请确保已构建项目：</p>
                    <pre style="background: #f5f5f5; padding: 1rem; border-radius: 4px; margin: 1rem 0;">
npm run build
                    </pre>
                </div>
            `;
        } else {
            // 调试信息
            console.log('ChicCore对象:', ChicCore);
            console.log('ChicCore.keys:', Object.keys(ChicCore));
            console.log('formatDate函数:', ChicCore.formatDate);
            
            // 获取ChicCore的导出对象
            const utils = ChicCore.default || ChicCore;
            // 创建Vue应用
            const app = createApp({
                data() {
                    return {
                        email: 'test@example.com',
                        storageKey: 'demo-key',
                        storageValue: 'demo-value',
                        loadedValue: '',
                        originalArray: [1, 2, 2, 3, 3, 3, 4, 5],
                        testObject: {
                            name: 'John',
                            age: 25,
                            address: {
                                city: 'New York',
                                country: 'USA'
                            }
                        },
                        uploadProgress: null,
                        selectedFiles: [],
                        validationResult: null,
                        isDragOver: false,
                        dropZoneController: null,
                        deduplicateResult: '',
                        cachedResult: '',
                        concurrencyResult: '',
                        treeResult: null,
                        findNodeResult: '',
                        treeStatsResult: '',
                        getRequestResult: '',
                        postRequestResult: '',
                        batchRequestResult: '',
                        httpConfigResult: '',
                        selectedFile: null
                    };
                },
                computed: {
                    formattedDate() {
                        return utils.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss');
                    },
                    relativeTime() {
                        const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
                        return utils.getRelativeTime(oneHourAgo);
                    },
                    capitalizedText() {
                        return utils.capitalize('hello world');
                    },
                    camelCaseText() {
                        return utils.camelCase('hello world example');
                    },
                    isEmailValid() {
                        return utils.isEmail(this.email);
                    },
                    uniqueArray() {
                        return utils.unique(this.originalArray);
                    },
                    groupedArray() {
                        const users = [
                            { name: 'John', age: 20, department: 'IT' },
                            { name: 'Jane', age: 25, department: 'HR' },
                            { name: 'Bob', age: 30, department: 'IT' }
                        ];
                        return utils.groupBy(users, 'department');
                    },
                    formattedNumber() {
                        return utils.formatNumber(1234.56, {
                            decimals: 2,
                            thousandsSeparator: ','
                        });
                    },
                    formattedCurrency() {
                        return utils.formatCurrency(1234.56, '¥', {
                            decimals: 2
                        });
                    },
                    formattedFileSize() {
                        return utils.formatFileSize(1048576); // 1MB
                    }
                },
                mounted() {
                    this.initDropZone();
                },
                beforeUnmount() {
                    if (this.dropZoneController) {
                        this.dropZoneController.destroy();
                    }
                },
                methods: {
                    initDropZone() {
                        if (this.$refs.dropZone) {
                            this.dropZoneController = utils.createFileDropZone(this.$refs.dropZone, {
                                onDrop: (files) => {
                                    console.log('拖拽文件:', files);
                                    this.selectedFiles = files;
                                },
                                onDragOver: () => {
                                    this.isDragOver = true;
                                },
                                onDragLeave: () => {
                                    this.isDragOver = false;
                                }
                            });
                        }
                    },
                    downloadTextFile() {
                        utils.downloadTextFile('Hello World!', 'hello.txt');
                    },
                    downloadJSONFile() {
                        const data = { name: 'Chic Core', version: '1.0.0', features: ['文件工具', '日期工具', '字符串工具'] };
                        utils.downloadJSONFile(data, 'chic-core-info.json');
                    },
                    handleFileUpload(event) {
                        const files = Array.from(event.target.files);
                        if (files.length > 0) {
                            console.log('选择的文件:', files);
                            this.selectedFiles = files;
                            
                            this.uploadProgress = 0;
                            const interval = setInterval(() => {
                                this.uploadProgress += 10;
                                if (this.uploadProgress >= 100) {
                                    clearInterval(interval);
                                    setTimeout(() => {
                                        this.uploadProgress = null;
                                    }, 1000);
                                }
                            }, 200);
                        }
                    },
                    async selectFiles() {
                        try {
                            const files = await utils.selectFiles({ 
                                multiple: true, 
                                accept: ['jpg', 'png', 'pdf', 'txt'] 
                            });
                            this.selectedFiles = Array.isArray(files) ? files : [files];
                            console.log('选择的文件:', this.selectedFiles);
                        } catch (error) {
                            console.error('文件选择失败:', error);
                        }
                    },
                    validateSelectedFile(event) {
                        const file = event.target.files[0];
                        if (file) {
                            this.validationResult = utils.validateFile(file, {
                                allowedTypes: ['image/jpeg', 'image/png'],
                                maxSize: 5 * 1024 * 1024, // 5MB
                                allowedExtensions: ['jpg', 'jpeg', 'png']
                            });
                            console.log('文件验证结果:', this.validationResult);
                        }
                    },
                    async testDeduplicateRequest() {
                        let callCount = 0;
                        const requestFn = async () => {
                            callCount++;
                            await new Promise(resolve => setTimeout(resolve, 100));
                            return `请求结果 ${callCount}`;
                        };

                        const startTime = Date.now();
                        const [result1, result2] = await Promise.all([
                            utils.deduplicateRequest('test-key', requestFn),
                            utils.deduplicateRequest('test-key', requestFn)
                        ]);
                        const endTime = Date.now();

                        this.deduplicateResult = `结果1: ${result1}, 结果2: ${result2}, 调用次数: ${callCount}, 耗时: ${endTime - startTime}ms`;
                    },
                    async testCachedRequest() {
                        let callCount = 0;
                        const requestFn = async () => {
                            callCount++;
                            return `缓存结果 ${callCount}`;
                        };

                        const result1 = await utils.cachedRequest('cache-key', requestFn);
                        const result2 = await utils.cachedRequest('cache-key', requestFn);

                        this.cachedResult = `结果1: ${result1}, 结果2: ${result2}, 调用次数: ${callCount}`;
                    },
                    async testConcurrencyControl() {
                        const results = [];
                        const createRequest = (id, delay) => async () => {
                            await new Promise(resolve => setTimeout(resolve, delay));
                            results.push(id);
                            return `请求 ${id}`;
                        };

                        const startTime = Date.now();
                        await Promise.all([
                            utils.controlledRequest(createRequest(1, 200), { priority: 1 }),
                            utils.controlledRequest(createRequest(2, 100), { priority: 2 }),
                            utils.controlledRequest(createRequest(3, 150), { priority: 0 })
                        ]);
                        const endTime = Date.now();

                        this.concurrencyResult = `执行顺序: ${results.join(', ')}, 耗时: ${endTime - startTime}ms`;
                    },
                    testArrayToTree() {
                        const testData = [
                            { id: 1, name: '根节点1', parentId: null },
                            { id: 2, name: '子节点1', parentId: 1 },
                            { id: 3, name: '子节点2', parentId: 1 },
                            { id: 4, name: '孙节点1', parentId: 2 },
                            { id: 5, name: '根节点2', parentId: null }
                        ];

                        this.treeResult = utils.arrayToTree(testData);
                    },
                    testFindTreeNode() {
                        if (!this.treeResult) {
                            this.testArrayToTree();
                        }

                        const node = utils.findTreeNode(this.treeResult, { id: 4 });
                        this.findNodeResult = node ? `找到节点: ${node.name}` : '未找到节点';
                    },
                    testTreeStats() {
                        if (!this.treeResult) {
                            this.testArrayToTree();
                        }

                        const depth = utils.getTreeDepth(this.treeResult);
                        const count = utils.getTreeNodeCount(this.treeResult);
                        const leaves = utils.getTreeLeaves(this.treeResult);

                        this.treeStatsResult = `深度: ${depth}, 节点数: ${count}, 叶子节点: ${leaves.length}`;
                    },
                    async testGetRequest() {
                        try {
                            const response = await utils.httpClient.get('/api/users', { page: 1, limit: 10 });
                            this.getRequestResult = `GET请求成功: ${JSON.stringify(response.data)}`;
                        } catch (error) {
                            this.getRequestResult = `GET请求失败: ${error.message}`;
                        }
                    },
                    async testPostRequest() {
                        try {
                            const data = { name: 'Test User', email: 'test@example.com' };
                            const response = await utils.httpClient.post('/api/users', data);
                            this.postRequestResult = `POST请求成功: ${JSON.stringify(response.data)}`;
                        } catch (error) {
                            this.postRequestResult = `POST请求失败: ${error.message}`;
                        }
                    },
                    handleFileUpload(event) {
                        this.selectedFile = event.target.files[0];
                    },
                    async testUploadRequest() {
                        if (!this.selectedFile) {
                            alert('请先选择文件');
                            return;
                        }

                        try {
                            const formData = new FormData();
                            formData.append('file', this.selectedFile);

                            const response = await utils.httpClient.upload('/api/upload', formData, {
                                onProgress: (percent) => {
                                    this.uploadProgress = percent;
                                }
                            });

                            this.uploadProgress = null;
                            alert(`上传成功: ${JSON.stringify(response.data)}`);
                        } catch (error) {
                            this.uploadProgress = null;
                            alert(`上传失败: ${error.message}`);
                        }
                    },
                    async testBatchRequest() {
                        try {
                            const requests = [
                                { method: 'get', url: '/api/users/1' },
                                { method: 'get', url: '/api/users/2' },
                                { method: 'get', url: '/api/users/3' }
                            ];

                            const result = await utils.httpClient.batch(requests, { concurrency: 2 });
                            this.batchRequestResult = `批量请求完成: 成功${result.successCount}个, 失败${result.errorCount}个`;
                        } catch (error) {
                            this.batchRequestResult = `批量请求失败: ${error.message}`;
                        }
                    },
                    testHttpConfig() {
                        const customClient = utils.createHttpClient({
                            baseURL: 'https://api.example.com',
                            timeout: 15000,
                            enableCache: true,
                            enableLogging: true
                        });

                        customClient.config.addRequestInterceptor((config) => {
                            config.headers['X-Custom-Header'] = 'ChicCore';
                            return config;
                        });

                        customClient.config.addResponseInterceptor((response) => {
                            console.log('响应拦截器:', response);
                            return response;
                        });

                        customClient.config.addErrorHandler(404, (error) => {
                            console.log('404错误处理:', error);
                        });

                        this.httpConfigResult = `自定义HTTP客户端创建成功: ${customClient.config.baseURL}`;
                    },
                    testDeepClone() {
                        const cloned = utils.deepClone(this.testObject);
                        cloned.name = 'Jane';
                        cloned.address.city = 'Los Angeles';
                        
                        this.deepCloneResult = `原对象城市: ${this.testObject.address.city}, 克隆对象城市: ${cloned.address.city}`;
                    },
                    saveToStorage() {
                        const success = utils.setLocalStorage(this.storageKey, this.storageValue);
                        if (success) {
                            alert('保存成功！');
                        } else {
                            alert('保存失败！');
                        }
                    },
                    loadFromStorage() {
                        this.loadedValue = utils.getLocalStorage(this.storageKey, '未找到数据');
                    }
                },
                template: `
                    <div class="vue-utils-demo">
                        <!-- 日期格式化示例 -->
                        <section class="demo-section">
                            <h2>日期工具</h2>
                            <div class="demo-item">
                                <label>当前时间格式化：</label>
                                <span>{{ formattedDate }}</span>
                            </div>
                            <div class="demo-item">
                                <label>相对时间：</label>
                                <span>{{ relativeTime }}</span>
                            </div>
                        </section>

                        <!-- 字符串处理示例 -->
                        <section class="demo-section">
                            <h2>字符串工具</h2>
                            <div class="demo-item">
                                <label>首字母大写：</label>
                                <span>{{ capitalizedText }}</span>
                            </div>
                            <div class="demo-item">
                                <label>驼峰命名：</label>
                                <span>{{ camelCaseText }}</span>
                            </div>
                            <div class="demo-item">
                                <label>邮箱验证：</label>
                                <input v-model="email" placeholder="输入邮箱" />
                                <span :class="{ valid: isEmailValid, invalid: !isEmailValid }">
                                    {{ isEmailValid ? '✓ 邮箱格式正确' : '✗ 邮箱格式错误' }}
                                </span>
                            </div>
                        </section>

                        <!-- 数组处理示例 -->
                        <section class="demo-section">
                            <h2>数组工具</h2>
                            <div class="demo-item">
                                <label>原数组：</label>
                                <span>{{ originalArray }}</span>
                            </div>
                            <div class="demo-item">
                                <label>去重后：</label>
                                <span>{{ uniqueArray }}</span>
                            </div>
                            <div class="demo-item">
                                <label>分组结果：</label>
                                <pre>{{ JSON.stringify(groupedArray, null, 2) }}</pre>
                            </div>
                        </section>

                        <!-- 格式化示例 -->
                        <section class="demo-section">
                            <h2>格式化工具</h2>
                            <div class="demo-item">
                                <label>数字格式化：</label>
                                <span>{{ formattedNumber }}</span>
                            </div>
                            <div class="demo-item">
                                <label>货币格式化：</label>
                                <span>{{ formattedCurrency }}</span>
                            </div>
                            <div class="demo-item">
                                <label>文件大小：</label>
                                <span>{{ formattedFileSize }}</span>
                            </div>
                        </section>

                        <!-- 文件工具示例 -->
                        <section class="demo-section">
                            <h2>文件工具</h2>
                            <div class="demo-item">
                                <label>文件下载：</label>
                                <button @click="downloadTextFile">下载文本文件</button>
                                <button @click="downloadJSONFile">下载JSON文件</button>
                            </div>
                            <div class="demo-item">
                                <label>文件选择：</label>
                                <button @click="selectFiles">选择文件</button>
                                <span v-if="selectedFiles.length > 0">
                                    已选择 {{ selectedFiles.length }} 个文件
                                </span>
                            </div>
                        </section>

                        <!-- 请求控制示例 -->
                        <section class="demo-section">
                            <h2>请求控制工具</h2>
                            <div class="demo-item">
                                <label>防重复请求：</label>
                                <button @click="testDeduplicateRequest">测试防重复请求</button>
                                <span>{{ deduplicateResult }}</span>
                            </div>
                            <div class="demo-item">
                                <label>缓存请求：</label>
                                <button @click="testCachedRequest">测试缓存请求</button>
                                <span>{{ cachedResult }}</span>
                            </div>
                        </section>

                        <!-- 树结构示例 -->
                        <section class="demo-section">
                            <h2>树结构工具</h2>
                            <div class="demo-item">
                                <label>数组转树：</label>
                                <button @click="testArrayToTree">测试数组转树</button>
                                <div v-if="treeResult" class="tree-result">
                                    <pre>{{ JSON.stringify(treeResult, null, 2) }}</pre>
                                </div>
                            </div>
                            <div class="demo-item">
                                <label>树节点查找：</label>
                                <button @click="testFindTreeNode">测试节点查找</button>
                                <span>{{ findNodeResult }}</span>
                            </div>
                            <div class="demo-item">
                                <label>树节点统计：</label>
                                <button @click="testTreeStats">测试树统计</button>
                                <span>{{ treeStatsResult }}</span>
                            </div>
                        </section>

                        <!-- HTTP请求示例 -->
                        <section class="demo-section">
                            <h2>HTTP请求工具</h2>
                            <div class="demo-item">
                                <label>GET请求：</label>
                                <button @click="testGetRequest">测试GET请求</button>
                                <span>{{ getRequestResult }}</span>
                            </div>
                            <div class="demo-item">
                                <label>POST请求：</label>
                                <button @click="testPostRequest">测试POST请求</button>
                                <span>{{ postRequestResult }}</span>
                            </div>
                            <div class="demo-item">
                                <label>批量请求：</label>
                                <button @click="testBatchRequest">测试批量请求</button>
                                <span>{{ batchRequestResult }}</span>
                            </div>
                        </section>
                    </div>
                `
            });
            
            app.mount('#app');
        }
    </script>
    
    <style>
        .vue-utils-demo {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            font-family: Arial, sans-serif;
        }

        .demo-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .demo-section h2 {
            margin-top: 0;
            color: #333;
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
        }

        .demo-item {
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .demo-item label {
            font-weight: bold;
            min-width: 120px;
        }

        .demo-item input {
            padding: 5px 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        .demo-item button {
            padding: 5px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .demo-item button:hover {
            background-color: #0056b3;
        }

        .valid {
            color: #28a745;
            font-weight: bold;
        }

        .invalid {
            color: #dc3545;
            font-weight: bold;
        }

        pre {
            background-color: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            overflow-x: auto;
            font-size: 0.9rem;
        }

        .tree-result {
            margin-top: 10px;
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 10px;
            background-color: #f8f9fa;
        }
    </style>
</body>
</html>
